const gulp = require('gulp'),
      htmlmin = require('gulp-htmlmin'),
      cleanCss = require('gulp-clean-css'),
      uglify = require('gulp-uglify'),
      babel = require('gulp-babel'),
      del = require('del'),
      connect = require('gulp-connect'),
      autoPrefixer = require('gulp-autoprefixer'),
      sass = require('gulp-sass')
    //   proxy = require('http-proxy-middleware')


const delDist = () => del('dist')
const paths = {
    html:{
        src:'src/**/*.html',
        dest:'dist'
    },
    css:{
        src:'src/css/**',
        dest:'dist/css'
    },
    js:{
        src:'src/js/**',
        dest:'dist/js'
    },
    img:{
        src:'src/images/**',
        dest:'dist/images'
    },
    libs:{
        src:'src/libs/**',
        dest:'dist/libs'
    },
    ico:{
        src:'src/favicon.ico',
        dest:'dist'
    }
}

const html = () => {
    return gulp.src(paths.html.src)
        .pipe(htmlmin({
            removeComments: true,//清除HTML注释
        	collapseWhitespace: true,//压缩HTML
        	collapseBooleanAttributes: true,//省略布尔属性的值 <input checked="true"/> ==> <input checked />
      		removeEmptyAttributes: true,//删除所有空格作属性值 <input id="" /> ==> <input />
      		removeScriptTypeAttributes: false,//删除<script>的type="text/javascript"
      		removeStyleLinkTypeAttributes: true,//删除<style>和<link>的type="text/css"
      		minifyJS: true,//压缩页面JS
      		minifyCSS: true//压缩页面CSS 
        }))
        .pipe(gulp.dest(paths.html.dest))
        .pipe(connect.reload())

}

const css = () => {
    return gulp.src(paths.css.src)
    .pipe(sass())
    // 添加浏览器前缀
    .pipe(autoPrefixer({
        presets: ['@babel/env']
    }))
    // .pipe(cleanCss())
    .pipe(gulp.dest(paths.css.dest))
    .pipe(connect.reload())

}

const js = () => {
    return gulp.src(paths.js.src)
    .pipe(babel({
        presets: ['@babel/env']
    }))
    .pipe(uglify())
    .pipe(gulp.dest(paths.js.dest))
    .pipe(connect.reload())
}
const img = () => gulp.src(paths.img.src).pipe(gulp.dest(paths.img.dest)).pipe(connect.reload())
const libs = () => gulp.src(paths.libs.src).pipe(gulp.dest(paths.libs.dest))

// 监听下面文件改变进行重启
const watch = () =>{
    gulp.watch(paths.html.src,html)
    gulp.watch(paths.css.src,css)
    gulp.watch(paths.js.src,js)
    gulp.watch(paths.img.src,img)
}

const server = () => {
    connect.server({
        root:'dist',
        port:4399,
        livereload:true,
       /*  middleware () {
            return [
              // 将以/api为开头的请求代理到域 http://localhost:80
              createProxyMiddleware('/api', {
                target: 'https://apiv2.pinduoduo.com',
                changeOrigin: true
              })
            ]
        } */
    })
}

//编写ico任务
const ico = () => gulp.src(paths.ico.src).pipe(gulp.dest(paths.ico.dest))

// 导出 
// default指默认任务
// series 是同步执行代码，要先删除了dist才能启动其他任务
// parallel 是异步执行任务，这些任务可以同时开启
module.exports.default = gulp.series(delDist,gulp.parallel(html,css,js,img,libs,watch,server,ico))  